/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.wdullaer.materialdatetimepicker.date;

import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.ListContainer;
import ohos.agp.components.Text;
import ohos.agp.text.Font;
import ohos.app.Context;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import com.wdullaer.materialdatetimepicker.ResourceTable;
import com.wdullaer.materialdatetimepicker.common.RecycleItemProvider2;
import com.wdullaer.materialdatetimepicker.common.ResourceUtils;
import com.wdullaer.materialdatetimepicker.date.DatePickerDialog.OnDateChangedListener;

/**
 * Displays a selectable list of years.
 */
public class YearPickerView extends ListContainer implements ListContainer.ItemClickedListener, OnDateChangedListener {
    private static final String TAG = "MonthFragment";
    private static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 1234567, TAG);

    private final DatePickerController mController;
    private YearAdapter mAdapter;
    private int mChildSize;
    private TextViewWithCircularIndicator mSelectedView;
    private Font font;

    public YearPickerView(Context context, DatePickerController controller, Font font) {
        super(context);
        this.font = font;
        mController = controller;
        mController.registerOnDateChangedListener(this);
        ComponentContainer.LayoutConfig frame = new ComponentContainer.LayoutConfig(LayoutConfig.MATCH_PARENT,
            LayoutConfig.MATCH_CONTENT);
        setLayoutConfig(frame);
        mChildSize = ResourceUtils.getDimensionPixelOffset(context, ResourceTable.Float_mdtp_year_label_height);
        setBoundaryFadeEffectEnable(true);
        setFadeEffectBoundaryWidth(mChildSize / 3);

        init();
        setItemClickedListener(this);
        onDateChanged();
    }

    private void init() {
        mAdapter = new YearAdapter(mController.getMinYear(), mController.getMaxYear());
        setItemProvider(mAdapter);
    }

    @Override
    public void onItemClicked(ListContainer parent, Component component, int position, long id) {
        mController.tryVibrate();
        TextViewWithCircularIndicator clickedView = (TextViewWithCircularIndicator) component;
        if (clickedView != null) {
            if (clickedView != mSelectedView) {
                if (mSelectedView != null) {
                    mSelectedView.drawIndicator(false);
                    mSelectedView.postLayout();
                }
                clickedView.drawIndicator(true);
                clickedView.postLayout();
                mSelectedView = clickedView;
            }
            mController.onYearSelected(getYearFromTextView(clickedView));
            mAdapter.notifyDataChanged();
        }
    }

    private static int getYearFromTextView(Text view) {
        return Integer.parseInt(view.getText());
    }

    private final class YearAdapter extends RecycleItemProvider2 {
        private final int mMinYear;
        private final int mMaxYear;

        YearAdapter(int minYear, int maxYear) {
            if (minYear > maxYear) {
                throw new IllegalArgumentException("minYear > maxYear");
            }
            mMinYear = minYear;
            mMaxYear = maxYear;
        }

        @Override
        public int getCount() {
            HiLog.warn(LABEL, "YearPickerView YearAdapter getCount:" + (mMaxYear - mMinYear + 1));
            return mMaxYear - mMinYear + 1;
        }

        @Override
        public Object getItem(int position) {
            return mMinYear + position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public Component getComponent2(int position, Component convertView, ComponentContainer parent) {
            HiLog.warn(LABEL, "YearPickerView getComponent2 position:" + position + ", parent:" + parent);
            TextViewWithCircularIndicator v;
            if (convertView != null) {
                v = (TextViewWithCircularIndicator) convertView;
            } else {
                v = (TextViewWithCircularIndicator) LayoutScatter.getInstance(parent.getContext())
                    .parse(ResourceTable.Layout_mdtp_year_label_text_view, parent, false);
                v.setAccentColor(mController.getAccentColor(), mController.isThemeDark());
            }
            if (font != null) {
                v.setFont(font);
            }
            int year = mMinYear + position;
            boolean selected = mController.getSelectedDay().year == year;
            v.setText(String.format(mController.getLocale(), "%d", year));
            v.drawIndicator(selected);
            v.postLayout();
            if (selected) {
                mSelectedView = v;
            }
            return v;
        }
    }

    public void postSetSelectionCentered(final int position) {
        new EventHandler(EventRunner.getMainEventRunner()).postTask(() -> {
            HiLog.warn(LABEL, "YearPickerView postTask postSetSelectionCentered position:" + position);
            scrollToCenter(position);
            setSelectedItemIndex(position);
        });
    }

    public int getFirstPositionOffset() {
        final Component firstChild = getComponentAt(0);
        if (firstChild == null) {
            return 0;
        }
        return firstChild.getTop();
    }

    @Override
    public void onDateChanged() {
        mAdapter.notifyDataChanged();
        postSetSelectionCentered(mController.getSelectedDay().year - mController.getMinYear());
    }
}
